<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="700px"
    @close="close"
  >
    <el-form ref="form" label-width="120px" :model="form" :rules="rules" :disabled="disabled">
      <el-form-item label="销售工单" prop="label">
        <el-input v-model="form.label" clearable placeholder="请输入"/>
      </el-form-item>
      <el-form-item label="销售日期" prop="sale_date">
        <el-date-picker v-model.trim="form.sale_date" clearable format="yyyy年MM月dd日"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="SKU" prop="sku_id">
         <el-select v-model="form.sku_id" placeholder="请选择" clearable filterable style="width: 400px;" @change="changeSku">
          <el-option v-for="(item,key) in skuList" :value="item.id" :key="key"
                     :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售数量" prop="number">
        <el-input-number style="width:150px" v-model.trim="form.number" :step="0.01" clearable @change="changeNumber"/>
      </el-form-item>
      <el-form-item label="计价单位" prop="unit">
        <el-select v-model.trim="form.unit" clearable >
          <el-option value="个"></el-option>
          <el-option value="KWH"></el-option>
          <el-option value="吨"></el-option>
          <el-option value="KG"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售单价" prop="unit_price">
        <el-input-number style="width:150px" :step="0.01" v-model.trim="form.unit_price" clearable @change="get_total_price"/>
      </el-form-item>
      <el-form-item label="销售金额" prop="total_price">
        <el-input-number style="width:150px" :step="0.01" v-model.trim="form.total_price" clearable/>
      </el-form-item>
      <el-form-item label="单位KWH" prop="unit_kwh">
        <el-input-number style="width:150px" :step="1"  v-model.trim="form.unit_kwh" clearable @change="get_total_kwh"/>
      </el-form-item>
      <el-form-item label="总KWH" prop="total_kwh">
        <el-input-number style="width:150px" :step="1"  v-model.trim="form.total_kwh" clearable/>
      </el-form-item>
      <el-form-item label="KWH单价" prop="kwh_unit_price">
        <el-input-number style="width:150px" :step="1"  v-model.trim="form.kwh_unit_price" clearable/>
      </el-form-item>
      <el-form-item label="下游客户" prop="customer_id">
        <el-select v-model.trim="form.customer_id" clearable filterable style="width:100%">
          <el-option v-for="(item,key) in customerList" :value="item.id" :key="key"
                     :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model.trim="form.remark" type="textarea"/>
      </el-form-item>
      <el-form-item label="上传附件" style="height:180px;margin-bottom: 30px">
        <template v-if="form.file_path">
          <el-link :href="fileRootPath+form.file_path" :underline="false" :download="form.file_path">
            <el-button icon="el-icon-download" size="small" type="success" plain>下载</el-button>
          </el-link>
          <el-link :underline="false">
            <el-button @click="delete_file" icon="el-icon-delete" type="danger" plain>删除</el-button>
          </el-link>
        </template>
        <template v-else>
          <attachment-upload typ="orderProduct" @input="changeUrl" ref="uploadFile"/>
          <p class="tips-words">ps:附件格式doc(x),xls(x),pdf,ppt(x),txt,zip,rar,7z,jp(e)g,png,gif,且不超过10M</p>
        </template>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :disabled="disabled" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>

import {getList as getAreaList} from '@/api/business/customer'
import AttachmentUpload from "@/views/other/upload/attachment";
import {getList as getSkuList} from "@/api/sku/classify";
import {doEdit} from "@/api/order/orderProduct";

export default {
  props: {
    customerList: {
      type: Array,
      required: true,
      default: () => [] // 默认为空数组
    },
    skuList: {
      type: Array,
      required: true,
      default: () => [] // 默认为空数组
    }
  },
  name: 'orderEdit',
  components: {AttachmentUpload},
  data() {
    return {
      sku_list:[],
      customer_list: [],
      disabled: false,
      form: {
        'address': [''],
        'connector': [
          {'name': '', 'tel': ''},
        ],
        'relationship': []
      },
      rules: {
        label: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        sale_date: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        sku_id: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        number: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        unit: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        unit_price: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        total_price: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        unit_kwh: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        total_kwh: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        customer_id: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        percentage: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        recycle_percentage: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
        kwh_unit_price: [
          {required: true, trigger: 'blur', message: '请填写'},
        ],
      },
      title: '',
      dialogFormVisible: false,
      fileRootPath: process.env.VUE_APP_FILE_ROOT_PATH

    }
  },
  created() {
    // this.handleQueryss()
  },
  methods: {
    changeSku(){
      if (this.form.sku_id){
        const skuItem = this.skuList.find(item => item.id === this.form.sku_id)
        const specItem = skuItem.attribute_spec.find(item => item.name === '标称能量kwh' || item.name === '标称能量KWH')
        if (specItem) {
          this.$set(this.form, 'unit_kwh', specItem.value.toFixed(10))
        } else {
          this.$set(this.form, 'unit_kwh', undefined)
        }
      }
    },
    changeNumber(){
      this.get_total_kwh()
      this.get_total_price()
    },
    get_total_price(){
      this.form.total_price = (this.form.unit_price*this.form.number).toFixed(2)
      this.get_kwh_unit_price()
    },
    get_kwh_unit_price(){
      if(this.form.unit === 'KWH') {
        this.form.kwh_unit_price = this.form.unit_price
      }else{
        this.form.kwh_unit_price = (this.form.unit_price / this.form.unit_kwh).toFixed(2)
      }
    },
    get_total_kwh(){
      this.form.total_kwh = (this.form.unit_kwh*this.form.number).toFixed(5)
      this.get_kwh_unit_price()
    },
    delete_file(){
      this.form.file_path = ''
    },
    changeUrl(data) {
      this.form.tempPath = data.tempPath
      this.form.fileType = data.fileType
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    showEdit(row) {
      if (!row) {
        this.title = '添加'
      } else {
        this.title = '编辑'
        this.form = Object.assign({}, row)
        this.form.temp_old = this.form.file_path
      }
      this.dialogFormVisible = true
      this.disabled = false
    },
    viewEdit(row) {
      this.title = '查看'
      this.form = Object.assign({}, row)
      this.dialogFormVisible = true
      this.disabled = true

    },
    close() {
      this.$refs['form'].resetFields()
      if(this.$refs['uploadFile'])
        this.$refs['uploadFile'].resetTempUrl()
      this.form = this.$options.data().form
      this.dialogFormVisible = false
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const {msg} = await doEdit(this.form)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.$emit('fetch-data')
          this.close()
        }
      })
    },
    handleQueryss() {
      getSkuList({'pageNo': 'all'}).then(({data}) => {
        this.sku_list = data.list;
      });
      getAreaList({'pageNo': 'all', 'relationship': '2'}).then(({data}) => {
        this.customer_list = data.list;
      });
    },
  },
}
</script>
<style scoped>
.row-with-margin {
  margin-bottom: 5px; /* 你可以根据需要调整这个值 */
}

.gap {
  /* 如果你已经有了gap类，确保它不会影响布局 */
}
</style>
